package com.ds.esd.bpm.custom.plugins.right;

import com.ds.common.util.CnToSpell;
import com.ds.esd.custom.tree.annotation.TreeAnnotation;
import com.ds.esd.tool.ui.component.list.TreeListItem;
import com.ds.esd.tool.ui.enums.SelModeType;
import com.ds.org.Org;
import com.ds.org.Person;
import com.ds.web.annotation.Pid;
import com.ds.web.annotation.Uid;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@TreeAnnotation(heplBar = true, caption = "选择人员", selMode = SelModeType.singlecheckbox)
public class PerformOrgTree extends TreeListItem {
    @Pid
    String orgId;
    @Uid
    String personId;

    public PerformOrgTree(Org org, List<Person> persons, List<Org> orgs, boolean hasPerson, String pattern) {
        this.setId(org.getOrgId());
        this.setCaption(caption);
        this.caption = org.getName();
        this.setId(org.getOrgId());
        imageClass = "bpmfont bpm-gongzuoliu-moxing";
        this.setIniFold(false);
        this.tagVar = new HashMap<>();
        this.tagVar.put("orgId", org.getOrgId());
        if (org.getPersonList() != null && org.getPersonList().size() > 0) {
            for (Person person : org.getPersonList()) {
                if (pattern(pattern, person) && persons.contains(person)) {
                    this.addChild(new PerformOrgTree(person));
                }
            }
        }
        List<Org> list = org.getChildrenList();
        Collections.sort(list);
        if (list.size() > 0) {
            for (Org childorg : org.getChildrenList()) {
                if (orgs.contains(childorg)) {
                    this.addChild(new PerformOrgTree(childorg, persons, orgs, hasPerson, pattern));
                }
            }
        }


    }


    private boolean pattern(String pattern, Person person) {
        if (pattern != null && !pattern.equals("")) {
            Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
            Matcher namematcher = p.matcher(person.getName());
            Matcher fieldmatcher = p.matcher(CnToSpell.getFullSpell(person.getName()));
            if (namematcher.find() || fieldmatcher.find()) {
                return true;
            }
        } else {
            return true;
        }
        return false;
    }


    public PerformOrgTree(Person person) {
        this.caption = person.getName();
        this.setId(person.getID());
        this.setIniFold(false);
        this.setImageClass("bpmfont bpmgongzuoliu");
        this.tagVar = new HashMap<>();
        this.tagVar.put("personId", person.getID());
    }

    public String getOrgId() {
        return orgId;
    }

    public void setOrgId(String orgId) {
        this.orgId = orgId;
    }

    public String getPersonId() {
        return personId;
    }

    public void setPersonId(String personId) {
        this.personId = personId;
    }
}
